//
//  DownloadViewController.m
//  ReadDemo
//
//  Created by YPShao on 2017/12/26.
//  Copyright © 2017年 YPShao. All rights reserved.
//

#import "DownloadViewController.h"
#import "AFNetworking.h"

@interface DownloadViewController ()

@property (nonatomic, strong) AFURLSessionManager *manager;
@property (nonatomic, strong) NSArray *dataSoruce;
@property (nonatomic, strong) NSMutableArray <NSURLSessionDownloadTask *> *taskArr;

@end

@implementation DownloadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSoruce = @[@"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/2a6a91419b7e541ae6fa9fbb97197ba9.mp3",
                        @"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/1ee258d06121000f7515ad3dc8552a4b.mp3",
                        @"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/47cb0b225b9f3da631d27633e98b8c1b.mp3",
                        @"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/075cff11a306738b4145a7eba484546f.mp3",
                        @"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/68809fbd8cd8cb108099ef985411265f.mp3",
                        @"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/4163c4770639152d4460f1871416d318.mp3",
                        @"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/fc5cac56816490a20544446c02362dcf.mp3",
                        @"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/526b45356d159ac0f6bfd3d33afd713d.mp3",
                        @"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/19bf87c66f6e15bcac09a814b34da3ab.mp3",
                        @"http://test-oss-public.zhimaezhan.cn/upload/2016/20160511/399896775/audio/f8df4446d3044d421a97fb924aef46b4.mp3",
                        ];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.HTTPMaximumConnectionsPerHost = 10;
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    self.manager = manager;
    for (int i = 0; i< self.dataSoruce.count  ; i++) {
        [self addDownlaodTaskWithUrlString:self.dataSoruce[i]];
    }
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(logDownloadTask) userInfo:nil repeats:YES];
}

- (NSMutableArray *)taskArr
{
    if (!_taskArr) {
        _taskArr = [NSMutableArray array];
    }
    return _taskArr;
}


- (void)addDownlaodTaskWithUrlString:(NSString *)urlString
{
    NSURL *URL = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSessionDownloadTask *downloadTask = [self.manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        NSLog(@"downloadProgress--->%@",downloadProgress);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"finish----->%@---error-->%@",response.URL,error);
    }];
    [downloadTask resume];
    [self.taskArr addObject:downloadTask];
}

- (void)logDownloadTask
{
    for (int i = 0; i< self.taskArr.count ; i++) {
        NSURLSessionDownloadTask *downloadTask  = self.taskArr[i];
        NSLog(@"downloadTask-->%@\n downloadProgress--->%@", downloadTask,[self.manager downloadProgressForTask:downloadTask]);
    }
}


- (void)downlaodTask
{
    //通过默认配置初始化Session
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    //设置网络请求序列化对象
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    [requestSerializer setValue:@"test" forHTTPHeaderField:@"requestHeader"];
    requestSerializer.timeoutInterval = 60;
    requestSerializer.stringEncoding = NSUTF8StringEncoding;
    //设置返回数据序列化对象
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer = responseSerializer;
    //网络请求安全策略
    if (/* DISABLES CODE */ (true)) {
        AFSecurityPolicy *securityPolicy;
        securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
        securityPolicy.allowInvalidCertificates = false;
        securityPolicy.validatesDomainName = YES;
        manager.securityPolicy = securityPolicy;
    } else {
        manager.securityPolicy.allowInvalidCertificates = true;
        manager.securityPolicy.validatesDomainName = false;
    }
    //是否允许请求重定向
    if (true) {
        [manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest *(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request) {
            if (response) {
                return nil;
            }
            return request;
        }];
    }
    //监听网络状态
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"%ld",(long)status);
    }];
    [manager.reachabilityManager startMonitoring];
    
    NSURL *URL = [NSURL URLWithString:@""];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
        NSLog(@"下载进度:%lld",downloadProgress.completedUnitCount);
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        NSLog(@"fileURL:%@",[fileURL absoluteString]);
        return fileURL;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];
    [downloadTask resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
